<?php

class event_dispatcher {

    public  $subscribers = array();
    const FOLDER_NAME = "evtsubs";
    protected function __construct() {
        ;
    }

    public static function i() {
        static $me = NULL;
        if ($me == NULL) {
            $me = new event_dispatcher();
        }
        return $me;
    }

    public function attach_subscriber(event_subscriber $obj) {
        if (!in_array($obj->event, array_keys($this->subscribers))) {
            $this->subscribers[$obj->event] = array();
        }
        $this->subscribers[$obj->event][] = $obj;
    }

    public function fire($event,$args=NULL) {
        if (count(@$this->subscribers[$event])) {
            foreach ($this->subscribers[$event] as $s) {
                if ($s->class_path !== NULL) {
                    include_once $s->class_path . "/" . $s->class_name . EXT;
                }                
                $class = $s->class;
                //$function = $s->function;
                //$args = $s->args;
                $obj = class_loader::new_obj($class);
                $obj->fire($args);
            }
        } 
    }

    public function attach_module_event_subscribers($module_name) {        
        $path = get_module_path($module_name, self::FOLDER_NAME);
        $listeners = get_filenames($path);        
        if ($listeners && count($listeners) > 0) {
            foreach ($listeners as $l) {              
              $class = class_loader::new_obj(basename($l, EXT));                
              $this->attach_subscriber($class->get_subscriber_obj());              
            }
        }
    }

}